package demo.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import javax.servlet.http.HttpServletRequest;


public class AccessFilter extends ZuulFilter {
    private static Logger logger = LoggerFactory.getLogger(AccessFilter.class);

    //过滤器类型,决定过滤器在请求生命周期中的哪一个阶段执行
    @Override
    public String filterType() {
        return "pre"; // 过滤器将在请求被路由之前得到执行
    }

    @Override
    public int filterOrder() {
        return 0; // 在请求生命周期的同一个阶段，存在多个过滤器时，的执行顺序
    }

    @Override
    public boolean shouldFilter() {
        return true; // 用来指定过滤器对哪些请求执行
    }

    @Override
    public Object run() { // 过滤器的具体逻辑
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
        Object accessToken = request.getParameter("accessToken");
        if(null == accessToken) {
            logger.warn("access token is empty!");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            return null;
        }
        logger.info("access token is ok.");
        return null;
    }
}
